package com.carhome.adapter;

import java.util.ArrayList;
import java.util.List;

import com.carhome.R;
import com.carhome.bean.json.CarBrandInfo;
import com.carhome.bean.json.CarInfo;
import com.carhome.bean.json.CarinfoList;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AlphabetIndexer;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CarFragmentAdapter extends BaseAdapter {
	private List<CarInfo> list;
	private BitmapUtils mBitmapUtils;
	private Context context;

	public CarFragmentAdapter(Context context, List<CarInfo> list) {
		this.list = list;
		this.context = context;
		mBitmapUtils = new BitmapUtils(context);
	}

	public int getCount() {
		return list.size();
	}

	@Override
	public CarInfo getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	private String lastLetter;

	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		if (convertView == null) {
			convertView = LayoutInflater.from(context).inflate(R.layout.car_fragment_listview_item,
					null);
			holder = new ViewHolder();
			holder.carBrandImg = (ImageView) convertView
					.findViewById(R.id.car_fragment_listItem_carImg);
			holder.carName = (TextView) convertView
					.findViewById(R.id.car_fragment_listItem_carName);
			holder.groupName = (TextView) convertView
					.findViewById(R.id.car_fragment_listItem_tvLetter);
			convertView.setTag(holder);
		} 
			holder = (ViewHolder) convertView.getTag();
			
		judeGroup(position, holder);
		
		mBitmapUtils.display(holder.carBrandImg, list.get(position).imgurl);
		holder.carName.setText(list.get(position).name);
		return convertView;
	}

	private void judeGroup(int position, ViewHolder holder) {
		// 获取每个车牌所属的字母分组
		String letter = getItem(position).getLetter();
		// 判断是否和上一个出现的字母是否相同，如果不相同则显示字母分组
		if (position != 0 && letter.equals(getItem(position-1).letter)) {
			holder.groupName.setVisibility(View.GONE);
		} else {
			holder.groupName.setVisibility(View.VISIBLE);
			holder.groupName.setText(letter);
		}
		lastLetter = letter;
	}

	private class ViewHolder {
		TextView groupName;
		ImageView carBrandImg;
		TextView carName;
	}
}
